<template>
	<div class="content-list">
		<list-title :data="header"></list-title>
		<div class="search">
			<el-form :inline="true" :model="searchForm" class="demo-form-inline">
				<el-form-item label="鉴品名称">
					<el-input v-model="searchForm.name" placeholder="鉴品名称" clearable></el-input>
				</el-form-item>
				<el-form-item label="添加时间">
					<el-date-picker
					v-model="searchForm.addTime"
					type="daterange"
					format="yyyy-MM-dd"
					value-format="yyyy-MM-dd"
					range-separator="至"
					start-placeholder="开始日期"
					end-placeholder="结束日期">
					</el-date-picker>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" size="mini" @click="searchSubmit">查询</el-button>
				</el-form-item>
			</el-form>
		</div>
		<list-table :list="contentList" :tableLoading="tableLoading" :footer="true" :pagination="pagination">
			<template v-slot:data>
				<el-table-column prop="name" label="鉴品名称" ></el-table-column>
				<el-table-column label="备案状态">
					<template slot-scope="scope">
						<span v-if="scope.row.state == 1"><el-tag type="success">备案成功</el-tag></span>
						<span v-if="scope.row.state == 2"><el-tag>待备案</el-tag></span>
						<span v-if="scope.row.state == 3"><el-tag type="warning">备案中</el-tag></span>
						<span v-if="scope.row.state == 4"><el-tag type="danger">备案失败</el-tag></span>
					</template>
				</el-table-column>
				<el-table-column prop="add_time" label="上传时间" width="150px"></el-table-column>
				<el-table-column label="操作" width="165">
					<template slot-scope="scope">
						<el-button type='text' size="mini" @click="transfer(scope.row)" v-if="auth.editor">转移</el-button>
						<el-button type='text' size="mini" @click="handleEdit(scope.$index, scope.row)" style="margin-left: 0px" v-if="auth.editor">编辑</el-button>
						<el-popover
						placement="top"
						width="100"
						@show="showQr(scope.row)"
						v-model="delTip[scope.$index+1]">
							<div class="del-tip" :ref="'qrCodeUrl' + scope.row.id" style="margin-bottom: 8px; padding-left: 12px;"></div>
							<div style="text-align: center; margin: 0">
								<el-button size="mini" type="text" @click="delTip.splice(scope.$index+1, 1, false)">关闭</el-button>
							</div>
							<el-button type="text" slot="reference" :disabled='submitLock[scope.$index+1]'>
								二维码
							</el-button>
						</el-popover>
						<!-- <el-button type="text" @mouseover="qrcode()">
							二维码
						</el-button> -->
						<el-popover
						placement="top"
						width="160"
						v-model="delTip[scope.$index+1]" v-if="auth.delete">
							<p class="del-tip"><span class="el-icon-question"></span>确定删除吗？</p>
							<div style="text-align: right; margin: 0">
								<el-button size="mini" type="text" @click="delTip.splice(scope.$index+1, 1, false)">取消</el-button>
								<el-button type="primary" size="mini" @click="handleDelete(scope.$index, scope.row)">确定</el-button>
							</div>
							<el-button type="text" slot="reference" :disabled='submitLock[scope.$index+1]'>
								删除 <span class="el-icon-loading" v-if='submitLock[scope.$index+1]'></span>
							</el-button>
						</el-popover>
					</template>
				</el-table-column>
			</template>
		</list-table>
		<!-- 转移分类 开始 -->
		<el-dialog :title="dialog.title" :visible.sync="dialog.visible" :close-on-click-modal="false" width="500px">
			<el-form :model="transferForm" :rules="rules" ref="transferForm" label-width="150px">
				<el-form-item label="转移到(可多选)" prop="parentid">
					<el-select v-model="transferForm.parentid" filterable placeholder="请选择栏目" @change="chooseCategory">
						<el-option label="顶级栏目" value="0"></el-option>
						<el-option v-for="(item, index) in categoryList" 
						:key="index" 
						:label="item.name" 
						:value="item.catid"
						:disabled="checkCatidsRepeat(item.catid)">
						</el-option>
					</el-select>
					<draggable :list="transferForm.data.catids" 
					:tag="'ul'" 
					class="category"
					:handle="sortOptions.handle" 
					:animation="sortOptions.animation" @update="dragEnd">
						<li v-for="(item, index) in transferForm.data.catids" :key="index" class="drag">
							<span>{{ item.name }}</span>
							<i @click.stop="removeCategory(index)">×</i>
						</li>
					</draggable>
					<p class="help">注：为首的栏目为主栏目，可拖动排序</p>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialog.visible = false">取 消</el-button>
				<el-button type="primary" @click="submitForm('transferForm')" :disabled='transferForm.submitLock'>
					确 定 <span class="el-icon-loading" v-if='transferForm.submitLock'></span>
				</el-button>
			</div>
		</el-dialog>
		<!-- 转移分类 结束 -->
	</div>
</template>

<script>
import ListTitle from "pc/common/Title"
import ListTable from "pc/common/ListTable"
import draggable from 'vuedraggable'
import {changeToBool, filterEmpty, judgeAuth, creatQrCode} from "static/js/common.js"
import {mapGetters} from 'vuex'
import QRCode from 'qrcodejs2'

export default {
	inject: ['reload'],
	data() {
		return {
			/*头部数据*/
			header: {
				title: '内容列表',
				reload: true,
				buttons: [
					{
						title: '添加内容',
						type: 'primary',
						pathName: 'pc/epi/pj8/Goods',
						auth: false,
						query: {
							catid: this.$route.query.catid,
							flag: this.$route.query.flag,
						},
					}
				]
			},
			dialog: {
				'title': '转移栏目',
				'visible': false,
			},
			auth: {
				list: true,//列表
				editor: true,//编辑
				delete: false,//删除
				audit: true,//审核
				sort: true,//排序
				changeState: true,//更改状态
			},
			/*搜索*/
			searchForm: {
				catid: this.$route.query.catid,
				name: this.$route.query.name,
				state: this.$route.query.state,
				addTime: (this.$route.query.begin_time!=undefined)?[this.$route.query.begin_time, this.$route.query.end_time]:'',
			},
			contentList: [],
			tableLoading: true,
			delTip: [],//刪除提示
			submitLock: [],
			stateLock: [],
			pagination: {
				count: 0,
				currPage: 1,
				pageSize: 3
			},
			/*批量操作*/
			batch: [
				// {
				// 	id: '5',
				// 	label: '批量回收'
				// },
				{
					id: '6',
					label: '批量删除'
				}
			],
			/*PC域名*/
			pc_url: '',
			/*转移分类*/
			/*拖拽插件参数*/
			sortOptions: {
				tag:'ul',//拖动句柄
				handle:'.drag',//拖动句柄
				animation: 80,//拖拽排序时，动画的多度时长
			},
			categoryList: [],//所有栏目，便于选择
			/*添加表单数据*/
			transferForm: {
				submitLock: false,
				parentid: '',//选择的栏目ID
				data: {
					id: 0,
					oldcatid: this.$route.query.catid,//之前的栏目ID
					catids: [
						// {
						// 	'catid': 1,
						// 	'name': '国内新闻',
						// }
					],
					mark: 'setCategory'//告诉后台，仅挪动栏目，后台需要把栏目的总数改变下
				}
			},
			rules: {
				data: {
					
				}
			}
		};
	},
	components: {
		ListTitle,
		ListTable,
		draggable
	},
	created: function() {

		/*获取所有企业数据*/
		this.getContentList()

		/*取出参数*/
		/*注释原因：内容列表里 已经返回了URL参数了，不需要再次获取*/
		// this.getConfig()

		/*获取当前选择的语言*/

		/*权限判断显示*/
		// this.header.buttons[0].auth = (judgeAuth('addContent', this.allMenuList) == undefined)?false:true
		// this.auth.audit = (judgeAuth('auditContent', this.allMenuList) == undefined)?false:true
		// this.auth.editor = (judgeAuth('modifyGoods', this.allMenuList) == undefined)?false:true
		// this.auth.delete = (judgeAuth('deleteGoods', this.allMenuList) == undefined)?false:true
		// this.$refs.qrCodeUrl3
		
	},
	// mounted() {
	// 	this.creatQrCode('qrCodeUrl', 'aaaa');
	// },
	methods: {
		/*获取内容列表*/
		getContentList: function(){
			if(this.$api.goodsList != undefined){
				this.$get(this.$api.goodsList, this.$route.query).then(res => {
					// console.log(res);
					if(res.data.code === 0){
						if(res.data.data.list != undefined && res.data.data.list.length > 0){
							// console.log(res.data.data.list, 111);
							this.contentList = []
							Object.keys(res.data.data.list).forEach((k) => {
								this.contentList.push (
									{
										id: res.data.data.list[k].goods_id,
										name: res.data.data.list[k].name,
										state: res.data.data.list[k].state,
										add_time: res.data.data.list[k].add_time,
									}
								);
							})
							this.pagination = res.data.data.pageInfo
						}
						if(res.data.data.url != undefined){
							// console.log(res.data.data.url)
							if(res.data.data.url.pc_url.indexOf("http://") == -1 && res.data.data.url.pc_url.indexOf("https://") == -1){
								this.pc_url = "http://" + res.data.data.url.pc_url
							}else{
								this.pc_url = res.data.data.url.pc_url
							}
						}
					}
				})
				.catch(err => {})
				.finally(() => {
					this.tableLoading = false
				}) 
			}else{
				this.$message({
					showClose: true,
					message: '没有内容列表的权限',
					type: 'error'
				});
			}
		},
		/*搜索提交*/
		searchSubmit: function(){
			let query = filterEmpty(JSON.parse(JSON.stringify(this.searchForm)))
			if(query.addTime != undefined){
				query = Object.assign({begin_time: query['addTime'][0], end_time: query['addTime'][1]}, query)
				delete query['addTime']
			}
			if(this.$route.query.haschild){//如果是所有内容列表
				query['catid'] = this.$route.query.catid
				query['haschild'] = this.$route.query.haschild
			}
			this.$router.push({query})
		},
		/*转移分类*/
		transfer(row){
			this.dialog.visible = !this.dialog.visible
			this.transferForm.data.id = row.id
			this.getGoodsCategoryList()
		},
		/*获取栏目 用户栏目转移*/
		getGoodsCategoryList: function(){
			if(this.$api.goodsCategoryList != undefined){
				this.$get(this.$api.goodsCategoryList).then(res => {
					// console.log(res);
					if(res.data.code === 0){
						if(res.data.data != undefined){
							this.categoryList = []
							Object.keys(res.data.data).forEach((k) => {
								let indent = '';
								for(var i=1; i<res.data.data[k].level; i++){
									if(i == 1){
										indent += '|---';
									}else{
										indent += '---';
									}
								}
								this.categoryList.push ({
									catid: res.data.data[k].catid,
									name: indent + res.data.data[k].name
								});
							})
						}
						this.tableLoading = false
					}
				})
				.catch(err => {})
				.finally(() => {}) 
			}
		},
		/*转移分类 选择栏目*/
		chooseCategory: function(val){
			/*遍历categoryList，找出选择的字段*/
			let obj = this.categoryList.find((item)=>{
				return item.catid === val;
			});
			let getName = obj.name;
			getName = getName.replace(/^\|\-+/,"");

			/*transferForm.data.catids里排重，不重复的就添加*/
			let has = false
			this.transferForm.data.catids.forEach((item, index) => {
				if(item.catid == val){
					has = true
				}
			})

			if(!has){
				this.transferForm.data.catids.push(
					{
						'catid': val,
						'name': getName,
					}
				)
			}
			this.transferForm.parentid = ''//选择内容清除，便于再次选择
		},
		/*转移栏目 删除栏目*/
		removeCategory(index) {
			this.transferForm.data.catids.splice(index, 1);
		},
		/*转移栏目 保存数据*/
		submitForm(formName, flag) {
			if(this.$api.modifyGoods != undefined){
				if(!this.transferForm.submitLock){
					this.$refs[formName].validate((valid) => {
						if (this.transferForm.data.catids.length) {
							// console.log(this.transferForm.data)
							this.transferForm.submitLock = true;
							/*添加、修改内容*/
							this.$post(this.$api.modifyGoods, {
								Goods: this.transferForm.data,
							}).then(res => {
								// console.log(res);
								/*成功*/
								if(res.data.code == 0){
									this.$message({
										showClose: true,
										message: res.data.info,
										type: 'success'
									});
									this.reload()
								}else{
									this.$message({
										showClose: true,
										message: res.data.info,
										type: 'error'
									});
								}
								this.transferForm.submitLock = false;
							});
						} else {
							this.$message({
								showClose: true,
								message: '请选择栏目',
								type: 'error'
							});
							return false;
						}
					});
				}
			}
		},
		/*重
		/*
		编辑 或 编辑
		audit 	true审核，false编辑
		*/
		handleEdit: function(index, row, audit = '') {
			this.$router.push(
				{
					name: 'pc/epi/pj8/Goods', 
					query: {
						id: row.id,
						catid: this.$route.query.catid,
						flag: this.$route.query.flag,
						audit: audit
					}
				}
			)
		},
		/*删除*/
		handleDelete: function(index, row) {
			if(this.$api.deleteGoods != undefined){
				if(!this.submitLock[index+1]){
					this.submitLock[index+1] = true//锁住当前的 删除按钮
					this.delTip.splice(index+1, 1, false)//提示消失
					/*请求后台删除*/
					this.$post(this.$api.deleteGoods, {
						'id': row.id
					}).then(res => {
						if(res.data.code == 0){
							this.$message({
								showClose: true,
								message: res.data.info,
								type: 'success'
							});
							this.contentList.splice(index, 1);//删除当前行
						}else{
							this.$message({
								showClose: true,
								message: res.data.info,
								type: 'error'
							});
						}
						this.submitLock[index+1] = false//释放当前的 删除按钮
					})
					.catch(err => {})
					.finally(() => {}) 
				}
			}
		},
		/*
		批量操作
		val 操作什么类型，批量删除，还是更改状态....
		data 需要操作的数据
		*/
		batchChange: function(flag, data) {
			// console.log(flag)
			// console.log(data)
			switch(flag) {
				case '5'://批量回收
					var api = this.$api.setContentState
					break
				case '6'://批量删除
					var api = this.$api.deleteGoods
					break
			}
			if(api != undefined){
				/*请求后台*/
				this.$post(api, {
					flag: flag,
					id: data,
				}).then(res => {
					if(res.data.code == 0){
						this.$message({
							showClose: true,
							message: res.data.info,
							type: 'success'
						});
						this.reload();
					}else{
						this.$message({
							showClose: true,
							message: res.data.info,
							type: 'error'
						});
					}
				})
				.catch(err => {})
				.finally(() => {}) 
			}
		},
		/*拖拽完毕，有排序变化才会触发*/
		dragEnd: function(){
			console.log("拖拽完毕")
		},
		showQr: function(row){
			// console.log(row.id)
			this.creatQrCode('qrCodeUrl' + row.id, row.id);
		},
		/*显示二维码*/
		creatQrCode(obj, v, h = 100, w = 100) {
			this.$refs[obj].innerHTML = ''
			// console.log(this.$refs[obj].innerHTML)
			var qrcode = new QRCode(this.$refs[obj], {
				text: v, // 需要转换为二维码的内容
				width: h,
				height: w,
				colorDark: '#000000',
				colorLight: '#ffffff',
				correctLevel: QRCode.CorrectLevel.H
			})
		}
	},
	computed: {
		/*验证 所属分类 是否已经选择了，不能再选*/
		checkCatidsRepeat(val) {
			return function (val) {
				let has = false
				this.transferForm.data.catids.find((item) => {
					if(val == item.catid){
						has = true
					}
				})
				return (has)
			}
		},
		...mapGetters([
			'allMenuList'
		])
	}
};
</script>

<style lang="stylus" scoped>
.content-list
	.warning
		color: #8a6d3b
		background-color: #fcf8e3
		border: 1px solid #faebcc
		margin-top: 10px
		padding: 10px
		font-size: 12px
		line-height: 20px
	.search
		margin-top: 10px
		.el-form-item--small.el-form-item
			margin-bottom: 0px

.category
	// border: red 1px solid
	padding-top: 10px
	width: 300px
	overflow: hidden
	li
		float: left
		border: #d6d6d6 1px solid
		margin-right: 10px
		margin-bottom: 10px
		cursor: pointer
		position: relative
		span
			display: block
			padding: 0 10px
			height: 100%
			font-size: 12px
 	li:hover i
		display: block
	li
		i
			width: 18px
			height: 18px
			line-height: 18px
			font-style: normal
			text-align: center
			color: #fff
			position: absolute
			display: inline-block
			border-radius: 100%
			background-color: rgba(0, 0, 0, .5)
			top: -9px
			right: -9px
			display: none
	li
		i:hover
			background-color: rgba(0, 0, 0, 1)


.cell
	>.el-button + .el-button
		margin-left: 0;
</style>